package servlet;

import dao.BlogDao;
import entity.Blog;
import entity.User;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhangYufei
 * Date: 2021-07-21
 * Time: 15:23
 */
@WebServlet("/blogList")
public class BlogListServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
    }

    //判断用户是否登录
    private User checkLogin(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            return null;
        }
        User user = (User) session.getAttribute("user");
        return user;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //0. 从req中读取当前用户信息，判定用户是否登录
        boolean isLogin = false;
        User user = checkLogin(req);
        if(user != null){
            isLogin = true;
        }
        //1.先从数据库查询有哪些博客
        BlogDao blogDao = new BlogDao();
        List<Blog> list = blogDao.selectAll();
        //2.构造博客页面
        //1) 通过 thymeleaf 进行渲染，渲染的时候需要定义一个"数据集合"的概念
        WebContext webContext = new WebContext(req, resp, getServletContext());
        //2) setVariable可以设置多个键值对，取决于模板代码怎么写
        // 模板中的每个 ${} 里面的内容都需要在 webContext 设定进去
        webContext.setVariable("list", list);
        webContext.setVariable("isLogin", isLogin);
        webContext.setVariable("user", user);
        //3) 进行渲染
        TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
        String html = engine.process("index", webContext);

        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(html);


        //使用字符串拼接的方式构造一个页面，该方式强烈不推荐
        /*StringBuilder html = new StringBuilder();
        for (Blog blog:list) {
            html.append("<div>");
            //标题，满足点击就可以跳转至详情页面，使用 a 标签
            html.append(String.format("<a herf = \"%s\">%s</a>","blogContent?blogId=" + blog.getBlogId() , blog.getTitle()));
            //发布时间
            html.append(String.format("<div>%s</div>",blog.getPostTime()));
            //博客摘要
            html.append(String.format("<div>%s</div>",blog.getContent().substring(0,50) + "..."));
            html.append("</div>");
        }*/
    }
}
